Java Statement
ποΈ Java Block Statements β Now with Extra Fun! πβ
π€ What is a Block Statement?β
Imagine you have a to-do list. You can complete each task one by one, or you can group similar tasks together (like βgroceriesβ or βwork stuffβ). Java does something similar with block statements! ποΈ
A block statement is just a bunch of Java statements wrapped up inside {}
curly braces. Why? Because sometimes Java needs you to use a single statement, but you have a whole bunch of them. So, put them in a block, and boom π₯βproblem solved!
π Exampleβ
{
int var = 20;
var++;
}
Simple, right? The statements inside {}
are treated as one. Like a coding burrito π―βall ingredients wrapped up nicely together.
π Scope of Variables Inside Blocks π΅οΈβ
Java is a bit territorial. If you declare a variable inside a block, it stays inside that block. It wonβt be available outsideβkind of like a top-secret club! π€«
β Example of Scope Violation π«β
{
int var = 20;
var++;
}
// Oh no! Java says NOPE! π¨
System.out.println(var); // ERROR: var is out of scope!
See? var
was declared inside the block, so Java refuses to acknowledge its existence outside of it. Typical Java. π
ποΈ Nested Blocksβ
You can nest blocks inside each other (like Russian dolls! π). Inner blocks can access variables from outer blocks, but outer blocks cannot access variables from inner blocks. Itβs like a VIP loungeβhigher-ups can enter, but the interns canβt sneak into the executive suite. π
π Blocks During Object Creationβ
Hereβs where things get spicy! πΆοΈ
Block statements donβt have to live inside methods! You can also use them inside classes to handle initialization logic.
π₯ Non-Static vs Static Blocksβ
- Non-static blocks β Run every time you create a new object. π
- Static blocks β Run only once when the class is loaded. π
Exampleβ
public class MyDemoAction {
private Integer variable = 10;
public MyDemoAction() {
System.out.println("MyDemoAction Constructor");
}
{
// Non-static block statement - runs every time an object is created!
System.out.println("Hello from a non-static block! ποΈ");
}
static {
// Static block statement - runs only once when the class loads!
System.out.println("Hello from a static block! π");
}
private void someMethod() {
System.out.println("HowToDoInJava.com");
}
}
π‘ What Happens When You Run This?β
- The static block executes first (only once).
- Each time you create an object, the non-static block runs before the constructor.
- Finally, the constructor runs.
This is Javaβs way of making sure certain setup tasks are done, with or without creating an object! π©β¨
π― The Takeawayβ
Thatβs all, folks! Now you know how to use block statements like a pro! π
β
Use {}
to group multiple statements into one.
β
Remember: variables inside a block stay inside the block.
β
Static blocks run once, while non-static blocks run every time an object is created.
Hope you had fun learning! Happy coding! ππ